package server;
import java.io.*;
import java.util.Arrays;

import msgs.*;

/**
 * Thread that sets/retrieves profiles for the admin
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */

public class AdminBLWorker extends Thread implements TTConstants {
	private AdminRequestMsg armsg;
	
	public AdminBLWorker(AdminMsg amsg) {
		this.armsg = (AdminRequestMsg) amsg;
	}
	
	public void run() {
		// can we yell at them to GTFO?
		if (!(Arrays.equals(armsg.getAdminKey(), TTServer.adminTable.get(armsg.getName()).getClientKey()))) {
			armsg.setResponse(Responses.DENY);
			AdminSender.outQ.add((AdminMsg) armsg);
			return;
		}
		
		// guess not.
		switch(armsg.getAction()) {
		case GETBL:
			File f = new File("data/buddylists/"+armsg.getUser());
			try {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
				// send back the buddylist they wanted
				Object o = ois.readObject();
				armsg.setO(o);
				ois.close();
			}
			catch (Exception e) {
				armsg.setO(null);
			}
			armsg.setResponse(Responses.OK);
			AdminSender.outQ.add((AdminMsg) armsg);
			break;
		case SETBL:
			//write the buddylist they wanted
			File dir = new File("data/buddylists");
			if (!(dir.exists())) dir.mkdirs();
			File person = new File("data/buddylists/"+armsg.getUser());
			try {
				ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(person));
				synchronized(TTConstants.lock) {
					oos.writeObject(armsg.getO());
				}
				oos.close();
				armsg.setResponse(Responses.OK);
				AdminSender.outQ.add((AdminMsg) armsg);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}
}
